import { onUnmounted, onMounted, createVNode, render } from 'vue';
import ConfirmDrillDownDialog from '@/views/design-center/screens/edit-screen/component/echart-dialog.vue';
import * as echarts from 'echarts';
import 'echarts-liquidfill';
import emitter from '@/utils/bus.js';
export const useEchart = (chartEl, props) => {
  let chart = null;

  const resizeHandler = (entry) => {
    const { width, height } = entry.contentRect;
    // console.log(width, height, 999999999999);
    chart?.resize({ width, height });
  };

  /**
   * @description:更新echarts图展示
   * @param {*} option
   * @return {*}
   */
  const updateEchart = (option) => {
    try {
      chart?.setOption(option);
    } catch (e) {
      console.log(e);
    }
  };

  /**
   * @description:双击echarts穿透
   * @param {*} param
   * @return {*}
   */
  const dblclickEchart = (searchData) => {
    //param.name x轴值,param.data y轴值

    console.log(
      '双击了----------',

      props.value.setups.penetrationSettings,

      searchData
    );

    const echartDialogNode = document.createElement('div');
    // echartDialogNode.onclick = () => {
    //   handleCancelCallBack();
    // };
    echartDialogNode.setAttribute(
      'style',
      `position: fixed;
             background-color: rgba(0, 0, 0, 0.5); 
             width: 100%; 
             height: 100%; 
             display: flex;
             justify-content: center;
             align-items: center;
             left: 0;
             right: 0; 
             top:0;
             bottom: 0;
             `
    );
    // console.log(document.body, 66666666, document.getElementById('app'));
    // document.body.appendChild(echartDialogNode);
    document.getElementById('bi-main').appendChild(echartDialogNode);

    // 封装组件属性方法
    const submitCallback = () => {
      // console.log('提交来了----------');
      //调用完毕后应该清空节点
      render(null, echartDialogNode);
      echartDialogNode.remove();
    };

    // 封装组件属性方法
    const handleCancelCallBack = () => {
      // console.log('取消来了----------');
      //清空节点
      render(null, echartDialogNode);
      echartDialogNode.remove();
    };

    // 在此处才创建节点并挂载属性
    const VNode = createVNode(ConfirmDrillDownDialog, {
      echartData: {
        name: '大屏',
        // penetrationSettings: props?.value?.setups?.penetrationSettings,
        setups: props?.value?.setups
        // currentXAxis: {
        //   ['a']: param.data //下钻查询参数
        // }
      },
      title: '图表弹框',
      submitText: '提交',
      cancelText: '取消',
      searchData: searchData,
      handleCancelCallBack,
      submitCallback
    });
    render(VNode, echartDialogNode);
  };

  onMounted(() => {
    if (chartEl.value) {
      chart = echarts.init(chartEl.value);
      chart.clear();
      if (props?.preview) {
        console.log('来了吗----------', props.value.type);

        let barAndLineArr = [
          'widget-area-chart',
          'widget-bar-columnar',
          'widget-bar',
          'widget-group-bar',
          'widget-group-line',
          'widget-line-bar',
          'widget-line',
          'widget-stacked-column',
          'widget-stacking-area'
        ];
        if (barAndLineArr.includes(props.value.type)) {
          //--- 双击穿透
          chart?.getZr().off('dblclick');
          chart?.getZr().on('dblclick', function (param) {
            //param.name x轴值,param.data y轴值
            console.log('双击穿透来了--------', param);
            let pointInPixel = [param.offsetX, param.offsetY];

            if (chart.containPixel('grid', pointInPixel)) {
              chart.getZr().setCursorStyle('pointer');
              let xIndex = chart.convertFromPixel({ seriesIndex: 0 }, [
                param.offsetX,
                param.offsetY
              ])[0];
              let handleIndex = Number(xIndex);
              let getOp = chart.getOption();
              let name = getOp.xAxis[0].data?.[handleIndex]; //获取点击的列名
              let xKey = getOp.xAxis[0].xKey;
              let searchData = `${xKey}='${name}'`;
              dblclickEchart(searchData);
            }
          });
        } else {
          chart?.off('dblclick');
          chart.on('dblclick', function (param) {
            //添加点击事件
            let xKey = param.data.xKey;
            let name = param.data.name;
            let searchData = `${xKey}='${name}'`;
            console.log('双击来了---------------', param, searchData);
            dblclickEchart(searchData);
          });
        }

        //---单击联动
        chart.getZr().off('click');
        chart?.getZr().on('click', function (param) {
          let pointInPixel = [param.offsetX, param.offsetY];
          if (chart.containPixel('grid', pointInPixel)) {
            chart.getZr().setCursorStyle('pointer');
            let xIndex = chart.convertFromPixel({ seriesIndex: 0 }, [
              param.offsetX,
              param.offsetY
            ])[0];
            let handleIndex = Number(xIndex);
            let getOp = chart.getOption();
            let xKey = getOp.xAxis[0].xKey; //获取点击的列名
            let name = getOp.xAxis[0].data[handleIndex]; //获取点击的列值

            // console.log('当前点击的索引', name, getOp);
            let setups = props.value.setups;
            console.log('点击联动来了--------', param, setups.linkageSetting);
            setups?.linkageSetting?.events?.forEach((element) => {
              element.linkageStatus &&
                emitter.emit(element.id, {
                  gangedCondition: `${xKey}='${name}'` //穿透/联动查询条件
                });
            });
          }
        });
      }
    }
  });

  onUnmounted(() => {
    if (chart) {
      chart.clear();
      chart.dispose();
    }
  });

  return { updateEchart, resizeHandler };
};
